package com.example.stream;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 终止流
 * 通过指定的函数来减少 Stream 中的元素，产生单个结果。
 */
public class TestReduce {

    String[] persons = new String[]{
            "政府办","区委办","政协","人大"
    };

    @Test
    public void testArray(){
        String result = Arrays.stream(persons).reduce("Start:", (s1, s2) -> s1 + s2);
        System.out.println(result);
        int[] counts = new int[]{1,2,4,5};
        int s = Arrays.stream(counts).reduce(10,(s1,s2)->s1*s2);
        System.out.println("s:"+s);
        int ss = Arrays.stream(counts).reduce(10,(s1,s2)->s1+s2);
        System.out.println("ss:"+ss);
    }

    @Test
    public void test(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        int sum = list.stream().reduce(0, Integer::sum); //求和
        int product = list.stream().reduce(1,(x,y)->x*y); //求积
        String str = list.stream().map(String::valueOf).reduce("",(x,y)->x+y); //字符串连接
    }

    @Test
    public void test2(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        Optional<Integer> max = list.stream().reduce((x,y)->x>y?x:y); //求最大值
        Optional<Integer> min = list.stream().reduce((x, y)->x<y?x:y);//求最小值
        Optional<Integer> result = list.stream().reduce((x, y)->x+y); //求和
        System.out.println("max:"+max.get()+",min:"+min.get()+",result:"+result.get());
    }

    @Test
    public void test3(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        long count = list.stream().count(); //元素个数
        Optional<Integer> find = list.stream().filter(x->x>3).findFirst(); //查找第一个大于3的元素
        Object[] array = list.stream().toArray(); //将元素转化为数组
    }
}
